package com.yike.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yike.common.exception.BusinessException;
import com.yike.common.tool.LoginUtil;
import com.yike.common.tool.StringUtil;
import com.yike.user.entity.MessageReminder;
import com.yike.user.mapper.MessageReminderMapper;
import com.yike.user.service.MessageReminderService;
import com.yike.user.param.MessageReminderPageParam;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yike.common.base.BaseServiceImpl;
import com.yike.common.pagination.Paging;
import com.yike.common.pagination.PageInfo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yike.user.vo.MessageReminderDateVo;
import com.yike.user.vo.MessageReminderInfoVo;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 消息提醒表 服务实现类
 *
 * @author Sakura
 * @since 2024-09-24
 */
@Slf4j
@Service
public class MessageReminderServiceImpl extends BaseServiceImpl<MessageReminderMapper, MessageReminder> implements MessageReminderService {

    @Autowired
    private MessageReminderMapper messageReminderMapper;

    @Override
    public List<MessageReminderDateVo> getMessageReminderList() throws Exception {
        // 获取当前用户所有的消息提醒记录
        List<MessageReminder> messageReminderDateVos = messageReminderMapper.selectList(
                Wrappers.lambdaQuery(MessageReminder.class)
                        .eq(MessageReminder::getUserId, LoginUtil.getUserId())
                        .orderByDesc(MessageReminder::getCreateTime));
        return groupMessageRemindersByDate(messageReminderDateVos);
    }

    // 根据日期分组数据
    public static List<MessageReminderDateVo> groupMessageRemindersByDate(List<MessageReminder> reminders) {
        // 定义日期格式化为 "yyyy-MM"
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        // 使用Stream对消息按照日期的 "yyyy-MM" 格式分组
        Map<String, List<MessageReminder>> groupedReminders = reminders.stream()
                .collect(Collectors.groupingBy(reminder -> sdf.format(reminder.getCreateTime())));

        // 构造返回的 MessageReminderDateVo 列表
        List<MessageReminderDateVo> result = new ArrayList<>();
        for (Map.Entry<String, List<MessageReminder>> entry : groupedReminders.entrySet()) {
            String date = entry.getKey(); // 按年月分组的日期
            List<MessageReminder> groupedList = entry.getValue();

            // 将 MessageReminder 转换为 MessageReminderInfoVo
            List<MessageReminderInfoVo> infoVos = groupedList.stream()
                    .map(reminder -> new MessageReminderInfoVo()
                            .setId(reminder.getId())
                            .setCorrelationId(reminder.getCorrelationId())
                            .setMsgType(reminder.getMsgType())
                            .setDescription(reminder.getDescription())
                            .setUserId(reminder.getUserId())
                            .setMsgStatus(reminder.getMsgStatus())
                            .setCheckStatus(reminder.getCheckStatus())
                            .setWebsocketStatus(reminder.getWebsocketStatus())
                            .setCreateTime(reminder.getCreateTime()))
                    .collect(Collectors.toList());

            // 构造MessageReminderDateVo
            MessageReminderDateVo dateVo = new MessageReminderDateVo()
                    .setDate(date)
                    .setInfoVos(infoVos);

            result.add(dateVo);
        }
        return result;
    }

    @Override
    public Paging<MessageReminderInfoVo> getMessageReminderPageList(MessageReminderPageParam messageReminderPageParam) throws Exception {
        // 处理开始日期和结束日期
        if (!StringUtil.isEmpty(messageReminderPageParam.getBeginTime())) {
            messageReminderPageParam.setBeginTime(messageReminderPageParam.getBeginTime() + " 00:00:00");
        }
        if (!StringUtil.isEmpty(messageReminderPageParam.getEndTime())) {
            messageReminderPageParam.setEndTime(messageReminderPageParam.getEndTime() + " 23:59:59");
        }

        Page<MessageReminder> page = new PageInfo<>(messageReminderPageParam);
        IPage<MessageReminderInfoVo> iPage = messageReminderMapper.getMessageReminderList(page, LoginUtil.getUserId(),
                messageReminderPageParam);
        return new Paging<MessageReminderInfoVo>(iPage);
    }

    @Override
    public Integer getMessageReminderCount() throws Exception {
        LambdaQueryWrapper<MessageReminder> queryWrapper = Wrappers.lambdaQuery(MessageReminder.class);
        queryWrapper.eq(MessageReminder::getUserId, LoginUtil.getUserId());
        queryWrapper.eq(MessageReminder::getMsgStatus, 0); // 未读
        return messageReminderMapper.selectCount(queryWrapper);
    }

    @Override
    public boolean read(Long id) throws Exception {
        MessageReminder messageReminder = messageReminderMapper.selectById(id);
        if (messageReminder == null || !messageReminder.getUserId().equals(LoginUtil.getUserId())) {
            throw new BusinessException("消息异常");
        }
        if (messageReminder.getMsgStatus() == 0) {
            messageReminder.setMsgStatus(1);
            messageReminder.setUpdateTime(new Date());
            messageReminderMapper.updateById(messageReminder);
        }

        return true;
    }

}
